<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/3/27
 * Time: 15:38
 */

namespace app\admin\controller;


use app\admin\controller\general\Config;
use app\admin\logic\VillageLogic;
use app\common\controller\Backend;
use app\common\utils\Constant;
use app\common\utils\PHPExcelUtils;
use app\common\utils\WeChatUtils;
use think\Db;
use think\Exception;

/**
 * 小区管理
 * Class Property
 * @package app\admin\controller
 */
class Village extends Backend
{
    protected $model = null;
    protected $relationSearch = true;

    public function _initialize(){

        parent::_initialize();
        //获取物业列表
        $userId = $this->auth->id;
        $user = model('User')->where(array('id'=>$userId))->field('user_type,property_id')->find();
        if($user['user_type'] == Constant::USER_TYPE_PROPERTY){
            $propertyList = model('Property')->where("id={$user['property_id']}")->select();
        }
        else{
            $propertyList = model('Property')->select();
        }
        $newPropertyList = [];
        foreach ($propertyList as $key=> $value){
            $newPropertyList[$value['id']] = $value['name'];
        }
        $this->view->assign('property_list', $newPropertyList);
        $this->model = model('Village');
    }

    /**
     * 查看
     * @param $ids='' 物业管理员id
     * @return mixed
     */
    public function index($ids='')
    {
        if ($this->request->isAjax())
        {
            $userId = $this->auth->id;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $user = model('User')->where(array('id'=>$userId))->field('user_type,property_id')->find();
//            $villageIds = $this->getVillageIds($user['property_id']);
            $map = [];
            if($user['user_type'] == Constant::USER_TYPE_PROPERTY) {
                $map['property_id'] = $user['property_id'];
            }
            $total = $this->model
                ->with('property')
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with('property')
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $key=>&$value){
                $value['province_name'] = model('Region')->where(array('id'=>$value['province_id']))->value('name');
                $value['county_name'] = model('Region')->where(array('id'=>$value['county_id']))->value('name');
                $value['city_name'] = model('Region')->where(array('id'=>$value['city_id']))->value('name');
            }
            unset($value);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->assignconfig('user_id',$ids);
        return $this->view->fetch();
    }

    /**
     * 添加
     * @param $ids='' 物业管理员id
     * @return mixed
     */
    public function add($ids='')
    {
        $userId = $this->auth->id;
        $user = model('User')->where(array('id'=>$userId))->field('user_type,property_id')->find();
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                $map['name'] = $params['name'];
//                $map['county_id'] = $params['county_id'];
                $count = $this->model->where($map)->count();
                if($count > 0){
                    $this->error('小区已经存在');
                }
//                $property_id = model('User')->where(array('id'=>$ids))->value('property_id');
//                $params['property_id'] = $property_id;
                $this->model->create($params);
                $this->success('添加成功');
            }
            $this->error('添加失败');
        }
        $this->assignconfig('user_type', $user['user_type']);
        $this->assignconfig('user_id',$ids);
        return $this->view->fetch();
    }

    /**
     * 编辑
     * @param $ids='' 小区id
     * @return mixed
     */
    public function edit($ids = '')
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                $map['name'] = $params['name'];
//                $map['county_id'] = $params['county_id'];
                $map['id'] = ['neq',$ids];
                $count = $this->model->where($map)->count();
                if($count > 0){
                    $this->error('小区已经存在');
                }
                $row->save($params);
                $this->success();
            }
            $this->error();
        }
        $this->assignconfig("village", $row);
        return $this->view->fetch();
    }


    /**
     * 删除
     * @param $ids='' 小区id
     * @return mixed
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            Db::startTrans();
            try {
                $result = $this->model->destroy($ids);
                if($result){
                    Db::commit();
                    $this->success('删除成功!');
                }else {
                    $this->error('删除失败!');
                }
            }catch (Exception $e){
                Db::rollback();
                $this->error('删除失败!');
            }

        }
        $this->error();
    }



    /**
     * 导入
     */
    public function import(){
        if ($this->request->isAjax())
        {
            ignore_user_abort();
            set_time_limit(0);
            $village_id = $this->request->post('village_id');
            $file_path = $this->request->post('file_path');
            $logic = new VillageLogic();
            $admin_id = $this->auth->id;
            $result = $logic->import($file_path,$village_id,$admin_id);
            $msg = '';
            $success = false;
            $rtnData = array();
            switch($result['status']){
                case 0:
                    $msg = $result['msg'];
                    break;
                case 1:
                    $success = true;
                    unlink($file_path);//删除文件
                    break;
                case 2:
                    $msg = $result['msg'];
                    break;
            }
            if($success){
                $this->success('导入成功！');
            }else{
                $this->error($msg,'',$rtnData);
            }
        }
        return $this->view->fetch();
    }

    /**
     *
     */
    public function send_message($ids = ''){
        if ($this->request->isAjax()) {
            $message = $this->request->post('message');
            if(empty($message)){
                $this->error('请填写发送内容');
            }
            if(empty($ids)){
                $this->error('请选择小区');
            }
            $villageLogic = new VillageLogic();
            $re = $villageLogic->sendMessage($ids, $message);
            $this->success();
        }
//        var_dump($ids);
        return $this->view->fetch();
    }

    /**
     * 小区导入模板
     */

    public function download_template(){
        $phpExcelUtil = new PHPExcelUtils();
        $cellList = array('业主姓名', '业主身份证', '房产详情', '需缴水费', '需缴物业费');
        $obj = $phpExcelUtil->setCellList($cellList);
        $fileName = iconv("utf-8", "gb2312", '小区缴费导入模板.xls');
        $obj->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }

    public function testAdd(){
        $data = [
            'name' => '中远方舟小区'
            ,'province_id' => 13
            ,'city_id'     => 153
            ,'county_id'   => 1541
            ,'address'     => '福建省厦门市集美区中远方舟小区'
            ,'property_id' => 1
        ];
        model('village')->insert($data);
    }


    public function testSend(){
        $weChat = \think\Config::get('WeChat');
        $wechatUtils = new WeChatUtils($weChat['app_id'], $weChat['app_secret'], $weChat['token']);
       var_dump($wechatUtils->sendCustomerMessage('oxSrk1aEp5DSv0TYsuS4LRAItCVQ', '321321321321'));
    }
}